// pages/publish/publish.js
const formTime = require('../../utils/formTime.js')
const db = wx.cloud.database()
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    college:[],
    img:[],
    index:0,
    time:formTime.formTime(new Date()),
    userinfo:''
  },

  // onSubscribe: function(){
  //   wx.requestSubscribeMessage({
  //     // tmplIds: ['t2r26N3WvkUIKJ3eMI1cpgoYlvvR3K6qpiHjpQmvQI4'],
  //     tmplIds: ['t2r26N3WvkUIKJ3eMI1cps-1oYn1-Sh5Y0Be89rOftM'],

  //     success(res){
  //       console.log('授权成功',res)
  //     },
  //     fail(res){
  //       console.log('授权失败',res)
  //     }
  //   })
  // },

	bindPickerChange: function (e) {
    //var index = this.data.index //记得要声明的，不然打印是undifind
    // console.log('picker发送选择改变，携带下标为', e.detail.value)
    // console.log('picker发送选择改变，携带值为', this.data.college[index])
    this.setData({
      index: e.detail.value,
    // type:this.data.college[index].name
    })
    },

  // 上传图片
  upload_img:function(){
    let that = this
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        wx.showLoading({
          title: '正在上传图片...'
        })
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        console.log("当前时间戳为：" + timestamp);
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log('linshi',tempFilePaths[0])
        wx.cloud.uploadFile({
          cloudPath: 'product/'+timestamp+'.png',
          filePath: tempFilePaths[0], // 文件路径
          success: function(res) {
            console.log('shangchuan',res)
            
            // wx.hideLoading();
            wx.cloud.callFunction({
              name:"imgSecCheck",
              data:{
                // value:tempFilePaths[0]
                value:res.fileID
              }
            }).then(
              imgRes => {
                console.log('imgRes',imgRes);
                if(imgRes.result.errCode == "87014"){
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  wx.showToast({
                    title: "图片含有违法违规内容",
                    icon: "none"
                  })
                }else{// 图片正常
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                        // get resource ID
                  console.log('res.fileID',res.fileID)
                  that.setData({
                    img:that.data.img.concat(res.fileID)
                  })
                }
              }
            )
            
          },
          fail: function(res) {
            // handle error
          }
        })
      }
    })
  },

  ViewImage(e){
    wx.previewImage({
      urls: this.data.img,
      current:e.currentTarget.dataset.url
    })
  },

  // 删除图片
  // 删除数组中指定下标
  delete: function (e) {
    let that = this
    console.log(that.data.img)
    console.log(e.currentTarget.dataset.id)
    var id = e.currentTarget.dataset.id;
    var img= that.data.img;
    img.splice(id,1)
    that.setData({
      img: img
    })
    wx.cloud.deleteFile({
      fileList: [e.currentTarget.dataset.src],
      success: res => {
        // handle success
        console.log(res.fileList)
      },
      fail: err => {
        // handle error
      },
    })
    console.log(that.data.img)
  },
  submit:function(e){
    // db.collection('message').skip(220).get({
    //   success: function(res) {
    //     console.log('success',res)
    //     for(let item of res.data){
    //       db.collection('message').doc(item._id).update({
    //         data:{
    //           done:false
    //         }
    //       })
    //     }
    //   },
    //   fail: function(res) {
    //     console.log('fail',res)
    //   }
    // })
    let that = this
    // console.log('要发布的书籍信息：',e)
    if(!wx.getStorageSync("userinfo")) {
      wx.showModal({
            title: '温馨提示',
            content: '该功能需要登录方可使用，是否马上去登录',
            success(res) {
                  if (res.confirm) {
                    wx.reLaunch({
                      url: '../my/my',
                    })
                  }
            }
      })
      return false
    }
    else{
      // this.onSubscribe()
      if(e.detail.value.name!==""&&e.detail.value.price!==""&&e.detail.value.fenlei!==""&&e.detail.value.detail!==""&&that.data.img.length!==0){
       console.log('i',e.detail.value.name+e.detail.value.price+e.detail.value.detail)
        wx.cloud.callFunction({
          name:'ContentCheck',
          data:{
            content:[e.detail.value.name+e.detail.value.price+e.detail.value.detail]
          },
          success(res) {
            console.log('ContentCheck-res',res)
            if (res.result.errCode == 87014) {
              console.log(res.errCode)
              wx.showToast({
                icon: 'error',
                title: '文字违规',
              })
            }else{
              db.collection('books').add({
                data:{
                  name:e.detail.value.name,
                  price:e.detail.value.price,
                  type:that.data.college[that.data.index].name,
                  detail:e.detail.value.detail,
                  src:that.data.img,
                  status:0,
                  time:that.data.time,
                  publisher:that.data.userinfo.nickName,
                  shoucang:[]
                  // product_xq_src:""
                },success:function(res){
                  wx.showToast({
                    title: '提交成功',
                  })
                  setTimeout(function(){
                    wx.reLaunch({
                      url: '../publish/publish',
                    })},500)
                }
              })
            }
          },fail(err){
            console.log('ContentCheck-err',err)
          }
        })
        
        
      }else{
        wx.showToast({
          title: '你还有未填信息',
          icon:"error"
        })
      }
    }
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      userinfo:wx.getStorageSync('userinfo')
    })
    db.collection('college').get({
      success:function(res){
        console.log('获取学院分类成功',res.data)
        that.setData({
          college:res.data
        })
      }
    })
    // that.setData({
    //   time:formTime.formTime(new Date())
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})